package com.oceansoft.mobile.econsole.modules.api.controller;

import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.complaint.entity.ComplaintReport;
import com.oceansoft.mobile.econsole.modules.complaint.entity.CompltCenter;
import com.oceansoft.mobile.econsole.modules.complaint.entity.CompltProInfo;
import com.oceansoft.mobile.econsole.modules.complaint.persistence.IComplaintMapper;
import com.oceansoft.mobile.econsole.modules.complaint.service.IComplaintService;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.sys.entity.SysUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.net.www.http.HttpClient;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Class: ApiComplaintController
 * Title: 一键报警(线索举报)
 * Desc: 一键报警功能接口
 * <p>
 * Created： shaom
 * Date： 2016/8/5
 */
@Controller
@RequestMapping(value = "api/complaint")
public class ApiComplaintController extends BaseController {

    @Resource
    private IComplaintMapper complaintMapper;

    @Resource
    private IComplaintService complaintService;
    @Resource
    private IWtMemberService wtMemberService;

    @RequestMapping(value = "index")
    public String gotoComplaintReportIndex(Model model) {
        return "weixin/complaintReport/inform_clew";
    }

    @RequestMapping(value = "save")
    public Result saveComplaintReport(HttpServletRequest request, Model model) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);

        SysUser user = (SysUser) request.getSession().getAttribute(Constant.SESSION_USER);
        List<MultipartFile> files = multipartRequest.getFiles("annex");
        for (MultipartFile f : files) {
            String name = f.getOriginalFilename();
        }
        return null;
    }

    /**
     * 获取线索举报接受部门一级菜单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "dept/first", method = GET)
    public Result getDealFirstDeptList() {
        return complaintService.loadDealFirstDeptList();
    }

    /**
     * 获取线索举报接受部门二级菜单
     *
     * @param deptId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "dept/second/{dept_id}", method = GET)
    public Result getDealSecDeptList(@PathVariable("dept_id") String deptId) {
        return complaintService.loadDealSecDeptList(deptId);
    }

    /**
     * 线索举报上传图片/视频
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "attach/upload", method = POST)
    public Result reportComplaintAttach(MultipartHttpServletRequest request) {
        List<MultipartFile> list = request.getFiles("photos");

        MultipartFile video = request.getFile("video");

        if (null == list && null == video) {
            return new Result(Result.FAILURE, "请上传图片或视频");
        }

        if (list.isEmpty() && video.isEmpty()) {
            return new Result(Result.FAILURE, "请上传图片或视频");
        }

        try {
            return complaintService.saveComplaintAttach(request);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "上传失败");
        }
    }





    /**
     * 线索举报上报
     */
    @ResponseBody
    @RequestMapping(value = "addComplaint", method = POST)
    public Result addComplaint(@RequestBody ComplaintReport complaintReport) {

        if (!complaintReport.isPass()) {
            return new Result(Result.FAILURE, "举报内容数据不合规！");
        }
        // 前台传
        complaintReport.setCrType(1);//1-线索举报 2-随手拍
//        complaintReport.setTemp7("999");//线索举报类型、随手拍类型
        return complaintService.addComplaintInfo(complaintReport);
    }

    /**
     * 12389投诉
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "proinfo/center", method = POST)
    public Result addComplaintCenter(HttpServletRequest request) {
        CompltProInfo compltProInfo = new CompltProInfo();
        compltProInfo.setGuid(UUID.randomUUID().toString());
        compltProInfo.setUnitAttribute(request.getParameter("unitAttribute"));
        compltProInfo.setProjectBillId("");
        SimpleDateFormat sf = new SimpleDateFormat("yyMMdd");

        //String projectBillId = complaintMapper.createProjectBillId();
        String lsh = complaintMapper.getProjectBillLsh();
        String pt = request.getParameter("pt");
        String projectBill = pt + "000020" + sf.format(new Date());

        // 警种
        String jz = request.getParameter("jzmc");
        String jzmc = "";
        if (jz.indexOf("-") >= 0) {
            String[] jzArr = jz.split("-");
            projectBill += jzArr[0];
            jzmc = jzArr[1];
        }


        // 4位流水号
        projectBill += String.format("%04d", Integer.parseInt(lsh));

        compltProInfo.setProjectBillId(projectBill);
        compltProInfo.setUnitName(request.getParameter("unitName"));
        compltProInfo.setUnitNumber(request.getParameter("unitNumber"));
        compltProInfo.setUnitAddress(request.getParameter("unitAddress"));
        compltProInfo.setHandPhone(request.getParameter("handPhone"));
        compltProInfo.setNetProjectCreatorGuid(request.getParameter("userGuid"));
        compltProInfo.setCreatorGuid(request.getParameter("userGuid"));
        compltProInfo.setUpDateGuid(request.getParameter("userGuid"));
        compltProInfo.setIsMydPj("0");
        compltProInfo.setProjectStatus("1");
        compltProInfo.setProjectStatusCn("已提交");
        compltProInfo.setIsCancelPrj("0");

        CompltCenter compltCenter = new CompltCenter();
        compltCenter.setGuid(UUID.randomUUID().toString());
        compltCenter.setProjectGuid(compltProInfo.getGuid());
        compltCenter.setJzmc(jzmc);
        compltCenter.setType(Integer.valueOf(request.getParameter("type") + ""));
        if (request.getParameter("type").equals("0")) {

//            compltCenter.setXb(request.getParameter("xb"));
            compltCenter.setTemp1(request.getParameter("jh"));
            compltCenter.setBjbrxm(request.getParameter("bjbrxm"));
            compltCenter.setZw(request.getParameter("zw"));
            compltCenter.setBjbrdw(request.getParameter("bjbrdw"));
            compltCenter.setRs(request.getParameter("rs"));

        } else {
            compltCenter.setBjbdwmc(request.getParameter("bjbdwmc"));
        }
        compltCenter.setJbsxTime(request.getParameter("jbsxTime"));
        compltCenter.setSxmc(request.getParameter("sxmc"));
        compltCenter.setJbsxjg(request.getParameter("jbsxjg"));

        return complaintService.addComplaintCenter(compltProInfo, compltCenter);
    }


    /**
     * 12389投诉列表/我的投诉列表
     *
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = POST)
    public Result loadComplaintByPage(@RequestBody Query query) {
        query.setNumPerPage(Constant.API_PAGE_SIZE);
        Result result = new Result();
        ApiPager returnPage = complaintService.loadComplaintByPage(query);
        result.setSucc(Result.SUCC);
        result.setData(returnPage);
        result.setMsg("获取投诉列表成功");
        result.setHasNext(returnPage.isHasNext());
        return result;
    }

    /**
     * 进入12389投诉页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "itComplt")
    public String gotoInsertComplaint(HttpServletRequest request, Model model) {
        WtMember member = getWxMemberSession();
        if (member != null) {
            model.addAttribute("loginUser", member);
            model.addAttribute("pt", request.getParameter("pt"));
            return "weixin/complaint/12389";
        }
        return null;
    }

    /**
     * 进入我的投诉页面
     *
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = "compltIndex")
    public String gotoComplaintIndex(Model model, Query query) {
        WtMember member = getWxMemberSession();
        query.setUserGuid(member.getGuid());
        query.setNumPerPage(Constant.API_PAGE_SIZE);
        ApiPager returnPage = complaintService.loadComplaintByPage(query);
        if (returnPage.getList().size() > Constant.API_PAGE_SIZE - 1) {
            model.addAttribute("noMore", 0);
            model.addAttribute("none", 0);
        } else if (returnPage.getList().size() <= Constant.API_PAGE_SIZE - 1 && returnPage.getList().size() > 0) {
            model.addAttribute("noMore", 1);
            model.addAttribute("none", 0);
        } else {
            model.addAttribute("noMore", 1);
            model.addAttribute("none", 1);
        }
        model.addAttribute("pager", returnPage);
        model.addAttribute("userGuid", member.getGuid());
        return "weixin/complaint/complaint_list";
    }

    /**
     * 根据12389投诉主键获取投诉回复
     *
     * @param projectGuid 12389投诉主键
     * @return Result
     */
    @RequestMapping(value = "reply/{projectGuid}", method = GET)
    public Result loadComplaintReply(@PathVariable("projectGuid") String projectGuid)
            throws IOException {
        return complaintService.loadComplaintReply(projectGuid);
    }

    /**
     * 进入我的投诉详情页面
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "compltDetail", method = POST)
    public String gotoComplaintDetails(HttpServletRequest request, Model model) {

        String projectGuid = request.getParameter("projectGuid");
        String userGuid = request.getParameter("userGuid");
        String userName = request.getParameter("userName");
        if (StringUtils.isBlank(userGuid) && StringUtils.isBlank(userName)) {
            userGuid = getWxMemberSession().getGuid();
            userName = getWxMemberSession().getAliasName();
        }

        model.addAttribute("projectGuid", projectGuid);
        model.addAttribute("userGuid", userGuid);
        model.addAttribute("userName", userName);
        return "weixin/complaint/complaint_detail";
    }

    /**
     * 根据12389投诉主键获取投诉详情
     *
     * @param projectGuid 12389投诉主键
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "detail/{projectGuid}", method = GET)
    public Result loadComplaintDetail(@PathVariable("projectGuid") String projectGuid)
            throws IOException {
        return complaintService.loadComplaintDetail(projectGuid);
    }


    /**
     * 大庆随手拍功能
     */
    /**
     * 跳转到随手拍--使用须知页面
     */
//    @RequestMapping(value = "wxphotopage", method = GET)
//    public String gotowxphotonotice(HttpServletRequest request, Model model){
//        model.addAttribute("userGuid",request.getParameter("userGuid"));
//        model.addAttribute("p",request.getParameter("p"));
//        return "weixin/weixinquery/photouploadnotice";
//    }
    /**
     * 跳转到微信随手拍页面 app 微信共用界面
     */
    @RequestMapping(value = "wxphotopage", method = GET)
    public String gotowxphoto(HttpServletRequest request, Model model) throws Exception {
        //首先判断是app还是微信
    //    String guid=request.getParameter("userGuid");
//        WtMember wtMember;
//        if(Strings.isNullOrEmpty(guid)){
//            //微信端
////            wtMember = getWxMemberSession();
//            model.addAttribute("platform",'W');
//        }else{
//            //app端
//            wtMember = wtMemberService.getWtMemberByUserGuid(guid);
            //首先判断是app :P ios:I  微信 :W
            model.addAttribute("platform",request.getParameter("p"));
        model.addAttribute("guid",UUID.randomUUID().toString().replaceAll("-", ""));
//            saveWxMemberSession(wtMember);
//        }
//
//        model.addAttribute("aliasName", wtMember.getAliasName());
//        model.addAttribute("telephone", wtMember.getUserName());
//        String userCode = wtMember.getUserCode();
//        if(!Strings.isNullOrEmpty(userCode) && !com.oceansoft.mobile.econsole.modules.weixin.config.Constant.isIDCard(userCode)){
//            userCode = DesAPPUtils.decrypt(wtMember.getUserCode());
//        }
//        model.addAttribute("idCard", userCode);

//        model.addAttribute("depts",complaintService.loadDealSecDeptList("230600000000").getData());

        return "weixin/weixinquery/photoupload";
    }

    /**
     * 保存随手拍表单。
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uploadphoto", method = GET)
    public Result saveComplaint(HttpServletRequest request)throws Exception {
        ComplaintReport complaintReport = new ComplaintReport();
       String guid=request.getParameter("guid");//获得guid
        //
        complaintReport.setGuid(guid);
        complaintReport.setContact(request.getParameter("xm").toString());//登录用户名
        complaintReport.setTemp2(request.getParameter("sjhm").toString());//联系电话
        complaintReport.setUserCode(request.getParameter("sfzhm").toString());//身份证号码
        complaintReport.setCrTitle(request.getParameter("bt").toString());//标题
        complaintReport.setCrContent(request.getParameter("jbnr").toString());//内容
        complaintReport.setCrType(Integer.valueOf(request.getParameter("wxjblx").toString()));//2 随手拍
        String xsly=request.getParameter("xsly");//平台bug
        if(StringUtils.isNotEmpty(xsly)){
            if("W".equals(xsly)){
                complaintReport.setXsly("W");
            }
            if((xsly).indexOf("A")!=-1){
                complaintReport.setXsly("A");
            }
            if((xsly).indexOf("I")!=-1){
                complaintReport.setXsly("I");
            }
        }
//        complaintReport.setUserGuid(getWxMemberSession().getGuid());//举报用户guid
        complaintReport.setUserGuid("");
        complaintReport.setDeptId("230600000000");//部门id
        complaintReport.setDeptName("大庆市公安局");//部门名称
        complaintReport.setTemp7(request.getParameter("temp7").toString());//举报类型，暂时未给出
        complaintReport.setAddress(request.getParameter("jtzz").toString());//具体地址
        Result result=complaintService.saveComplain(complaintReport);
        return result;


    }

}
